#!/usr/bin/perl -w
use strict;
use Getopt::Long;

my $suffix = 'pileup_filtered';
GetOptions(
	's|suffix:s' => \$suffix,
	);
my $dir = shift || ".";

opendir(DIR,$dir) || die $!;
my %dat_summary;
my %strains;
for my $file ( readdir(DIR) ) {
  next unless ( $file =~ /(\S+)\.(\S+)\.\Q$suffix\E$/);
  my ($strain,$ref_genome) = ($1,$2);
  $strains{$strain}++;
  open(my $fh => "$dir/$file") || die "$dir/$file: $!";
  while (<$fh>) {
    chomp;
    my ($chrom,$basepair,$ref_allele, $read_allele, 
	$consensus_qual, $snp_quality, $max_map_qual,
	$read_base_info, $base_qualities) = split(/\t/,$_);
    $dat_summary{$ref_genome}->{$chrom}->{$basepair}->{$strain} = $read_allele;
    if ( ! exists $dat_summary{$ref_genome}->{$chrom}->{$basepair}->{$ref_genome} ) {
      $dat_summary{$ref_genome}->{$chrom}->{$basepair}->{$ref_genome} = $ref_allele;
    } elsif ( $dat_summary{$ref_genome}->{$chrom}->{$basepair}->{$ref_genome} ne
	      $ref_allele ) {
      warn("ref allele disagrees! $ref_allele -> ",
	   $dat_summary{$ref_genome}->{$chrom}->{$basepair}->{$ref_genome},
	   "\n");
      if ( $ref_allele ne '*' ) {
	$dat_summary{$ref_genome}->{$chrom}->{$basepair}->{$ref_genome} = $ref_allele;
      }
    }
  }
}

my @strains = sort keys %strains;
while ( my ($ref,$d) = each %dat_summary ) {
  open(my $ofh => ">$ref.SNPs.dat") || die $!;
  print $ofh join("\t", qw(CHROM POS), "ref_".$ref, @strains), "\n";
  for my $chrom ( keys %$d ) {
    for my $pos ( sort { $a <=> $b } keys %{$d->{$chrom}} ) {
      print $ofh join("\t", $chrom,$pos,
		      map { $d->{$chrom}->{$pos}->{$_} || '-'} ($ref,@strains)),"\n";
    }
  }
}
